<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="js/vue-qriously.js"></script>
    <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="js/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>

<body>
    <div id="app">
        <div class="container">
            <!-- 手机登录 #start -->
            <div class="operate-view" v-if="dialogAtrr.showLoginType === 'phone'">
                <div class="wrapper" style="width: 100%">
                    <div class="mobile-wrapper" style="position: static; width: 70%">
                        <span class="title">{{ dialogAtrr.labelTips }}</span>
                        <el-form>
                            <el-form-item>
                                <el-input v-model="dialogAtrr.inputValue" :placeholder="dialogAtrr.placeholder"
                                    :maxlength="dialogAtrr.maxlength" class="input v-input">
                                    <span slot="suffix" class="sendText v-link" v-if="dialogAtrr.second > 0">{{
                                        dialogAtrr.second }}s
                                    </span>
                                    <span slot="suffix" class="sendText v-link highlight clickable selected"
                                        v-if="dialogAtrr.second == 0" @click="getCodeFun()">重新发送
                                    </span>
                                </el-input>
                            </el-form-item>
                        </el-form>
                        <div class="send-button v-button" @click="btnClick()">
                            {{ dialogAtrr.loginBtn }}
                        </div>
                    </div>
                    <div class="bottom">
                        <div class="wechat-wrapper" @click="weixinLogin()">
                            <span class="iconfont icon"></span>
                        </div>
                        <span class="third-text"> 第三方账号登录 </span>
                    </div>
                </div>
            </div>
            <!-- 手机登录 #end -->

            <!-- 微信登录 #start -->
            <div class="operate-view" v-if="dialogAtrr.showLoginType === 'weixin'">
                <div class="wrapper wechat" style="height: 400px">
                    <div>
                        <div id="weixinLogin"></div>
                    </div>
                    <div class="bottom wechat" style="margin-top: -80px">
                        <div class="phone-container">
                            <div class="phone-wrapper" @click="phoneLogin()">
                                <span class="iconfont icon"></span>
                            </div>
                            <span class="third-text"> 手机短信验证码登录 </span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 微信登录 #end -->
        </div>

    </div>
</body>

</html>

<script>
    const defaultDialogAtrr = {
        showLoginType: "phone", // 控制手机登录与微信登录切换

        labelTips: "手机号码", // 输入框提示

        inputValue: "", // 输入框绑定对象
        placeholder: "请输入您的手机号", // 输入框placeholder
        maxlength: 11, // 输入框长度控制

        loginBtn: "获取验证码", // 登录按钮或获取验证码按钮文本

        sending: true, // 是否可以发送验证码
        second: -1, // 倒计时间  second>0 : 显示倒计时 second=0 ：重新发送 second=-1 ：什么都不显示
        clearSmsTime: null, // 倒计时定时任务引用 关闭登录层清除定时任务
    };


    new Vue({
        el: '#app',
        data() {
            return {
                userInfo: {
                    phone: "",
                    code: "",
                    openid: "",
                },

                // 弹出层相关属性
                dialogAtrr: defaultDialogAtrr,

                name: "", // 用户登录显示的名称

            };
        },
        created() {
            this.showInfo();

            console.log(sessionStorage.getItem("name"))
        },
        mounted() {
            // 注册全局登录事件对象
            window.loginEvent = new Vue();
            // 监听登录事件
            loginEvent.$on('loginDialogEvent', function () {
                window.location.href = 'login.html';
            })
            // 触发事件，显示登录层：loginEvent.$emit('loginDialogEvent')

            //初始化微信js
            const script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
            document.body.appendChild(script)

            // 微信登录回调处理
            window["loginCallback"] = (name, token) => {
                this.loginCallback(name, token);
            }

        },
        methods: {
            //微信回调方法
            loginCallback(name, token, openid) {
                // 打开手机登录层，绑定手机号，改逻辑与手机登录一致
                this.setCookies(name, token)
            },
            showInfo() {
                let token = this.getCookie("token");
                if (token) {
                    this.name = this.getCookie("name");
                }
            },
            phoneLogin() {
                this.dialogAtrr.showLoginType = "phone";
                this.showLogin();
            },
            // 绑定登录，点击显示登录层
            showLogin() {
                this.dialogUserFormVisible = true;

                // 初始化登录层相关参数
                this.dialogAtrr = { ...defaultDialogAtrr };
            },
            // 绑定登录或获取验证码按钮
            btnClick() {
                // 判断是获取验证码还是登录
                if (this.dialogAtrr.loginBtn == "获取验证码") {
                    this.userInfo.phone = this.dialogAtrr.inputValue;

                    // 获取验证码
                    this.getCodeFun();
                } else {
                    // 登录
                    this.login();
                }
            },
            // 获取验证码
            getCodeFun() {
                if (!/^1[34578]\d{9}$/.test(this.userInfo.phone)) {
                    this.$message.error("手机号码不正确");
                    return;
                }

                // 初始化验证码相关属性
                this.dialogAtrr.inputValue = "";
                this.dialogAtrr.placeholder = "请输入验证码";
                this.dialogAtrr.maxlength = 6;
                this.dialogAtrr.loginBtn = "马上登录";

                // 控制重复发送
                if (!this.dialogAtrr.sending) return;

                // 发送短信验证码
                this.timeDown();
                this.dialogAtrr.sending = false;
                axios.get(`http://localhost:8204/api/msm/send/${this.userInfo.phone}`)
                    .then((response) => {
                        this.timeDown();
                    })
                    .catch((e) => {
                        this.$message.error("发送失败，重新发送");
                        // 发送失败，回到重新获取验证码界面
                        this.showLogin();
                    });
            },
            // 倒计时
            timeDown() {
                if (this.clearSmsTime) {
                    clearInterval(this.clearSmsTime);
                }
                this.dialogAtrr.second = 60;

                this.dialogAtrr.labelTips = "验证码已发送至" + this.userInfo.phone;
                this.clearSmsTime = setInterval(() => {
                    --this.dialogAtrr.second;
                    if (this.dialogAtrr.second < 1) {
                        clearInterval(this.clearSmsTime);
                        this.dialogAtrr.sending = true;
                        this.dialogAtrr.second = 0;
                    }
                }, 1000);
            },
            // 登录
            login() {
                this.userInfo.code = this.dialogAtrr.inputValue;

                if (this.dialogAtrr.loginBtn == "正在提交...") {
                    this.$message.error("重复提交");
                    return;
                }
                if (this.userInfo.code == "") {
                    this.$message.error("验证码必须输入");
                    return;
                }
                if (this.userInfo.code.length != 6) {
                    this.$message.error("验证码格式不正确");
                    return;
                }
                this.dialogAtrr.loginBtn = "正在提交...";
                axios.defaults.headers.post['Content-Type'] = 'application/json'


                axios.post(`http://localhost:8160/api/user/login`, JSON.stringify(this.userInfo))
                    .then((response) => {
                        // 登录成功 设置cookie
                        this.setCookies(response.data.data.name, response.data.data.token);
                    })
                    .catch((e) => {
                        this.dialogAtrr.loginBtn = "马上登录";
                    });
            },
            weixinLogin() {
                this.dialogAtrr.showLoginType = "weixin";
                axios.get(`http://localhost:8160/api/ucenter/wx/getLoginParam`)
                    .then(response => {
                        console.log(response.data.data)
                        var obj = new WxLogin({
                            self_redirect: true,
                            id: 'weixinLogin', // 需要显示的容器id
                            appid: response.data.data.appid, // 公众号appid wx*******
                            scope: response.data.data.scope, // 网页默认即可
                            redirect_uri: response.data.data.redirect_uri, // 授权成功后回调的url
                            state: response.data.data.state, // 可设置为简单的随机数加session用来校验
                            style: 'black', // 提供"black"、"white"可选。二维码的样式
                            href: '' // 外部css文件url，需要https
                        })
                    })
            },
            setCookies(name, token) {
                this.addCookie("token", token, 10);
                this.addCookie("name", name, 10);
                window.location.reload();
            },
            //添加cookie
            addCookie(name, value) {
                // 设置cookie的名称、值
                document.cookie = cookieName + "=" + value;
            },
            //获取cookie
            getCookie(name) {
                //获取当前所有cookie
                var strCookies = document.cookie;
                //截取变成cookie数组
                var array = strCookies.split('; ');
                //循环每个cookie
                for (var i = 0; i < array.length; i++) {
                    //将cookie截取成两部分
                    var item = array[i].split("=");

                    //判断cookie的name 是否相等
                    if (item[0] == name) {
                        return item[1];
                    }
                }
                return null;
            },
        }
    })

</script>